package com.work.demo.juctest;

import sun.misc.Unsafe;

/**
 * @ClassName : CASTest
 * @Description :
 * @Author : LinYa
 * @Date: 2021/11/15  10:48
 */
public class CASTest {

	public static void main(String[] args) {
		Entity entity = new Entity();
		Unsafe unsafe = UnsafeFactory.getUnsafe();
		long offset = UnsafeFactory.getFieldOffset(unsafe, Entity.class, "x");

		boolean successful;
		//偏移量 对象头占8个字节， 类型指针(int占四个字节)  偏移量是12  ，如果对象在增加一个属性，则再增加相应的偏移量  对齐填充位
		// 4个参数分别是：对象实例、字段的内存偏移量、字段期望值、字段新值
		successful = unsafe.compareAndSwapInt(entity, offset, 0, 3);
		System.out.println(successful + "\t" + entity.x);

		successful = unsafe.compareAndSwapInt(entity, offset, 3, 5);
		System.out.println(successful + "\t" + entity.x);

		successful = unsafe.compareAndSwapInt(entity, offset, 4, 8);
		System.out.println(successful + "\t" + entity.x);

	}


}

class Entity {
	int x;
}
